AJS.toInit(function ($) {
	"use strict";
	var deleteDialog = null, renameDialog = null, mergeDialog = null,
		// change href of #space-labels-link and #space-labels-link-tab menu items on space
		spaceKey = AJS.$("#confluence-space-key").attr("content"),
		// --------------------Delete Dialog--------------------
		// This is called when ajax completed from delete action
		onDeleteLabelByAjaxCompleted = function (data) {
			// if action success then reload page, else show the error message
			if (data.success === true) {
				// build redirect url
				var spaceKey = AJS.$('#label-delete-form input[name="spaceKeyCurrent"]').val(),
					keyParam = (spaceKey === '') ? '' : '?key=' + spaceKey,
					redirectUrl = Confluence.getContextPath()
									+ "/labels/listlabels-management.action"
									+ keyParam;
				// redirect action
				window.location = redirectUrl;
			} else {
				// show error message
				AJS.$('#label-delete-form #labelOperationErrorMessage').html(data.response);
				AJS.$('#label-delete-form .error-row').show();
			}
		},

		// This function process the submit delete form event 
		onSubmitDeleteForm = function () {
			var request = {
				url: Confluence.getContextPath() + "/labels/deletelabel.action",
				data: {},
				dataType: "json",
				type: "GET",
				success: onDeleteLabelByAjaxCompleted
			};
			// set request data
			request.data['label'] = AJS.$('#label-delete-form input[name="label"]').val();
			request.data['spaceKey'] = AJS.$('#label-delete-form input[name="spaceKey"]:checked').val();
			// call ajax request
			AJS.safe.ajax(request);
		},

		// This function create the delete dialog and bind its events
		initDialogDelete = function () {
			deleteDialog = AJS.ConfluenceDialog({
				width : 550,
				height : 210,
				id : "delete-labels-dialog",
				closeOnOutsideClick: false
			});
			
			deleteDialog.addHeader("");
			deleteDialog.addPanel("Label Editor", AJS.renderTemplate("labels-dialog-delete"));
			deleteDialog.addHelpText(AJS.I18n.getText("label.manager.dialog.shortcut.tip"), {shortcut: "x"});
			deleteDialog.addSubmit(AJS.I18n.getText("delete.name"), onSubmitDeleteForm);
			deleteDialog.addCancel(AJS.I18n.getText("close.name"), function (dialog) {
				$('#defaultOnSpace').attr('checked', 'checked');
				AJS.$('.errorMessage').html("");
				dialog.hide();
			});
		},

		// This function show delete dialog
		showDeleteDialog = function () {
			// init dialog if necessary
			if (!deleteDialog) {
				initDialogDelete();
			}
			// set data for the form
			var label,
				headerText = '';
			if (AJS.$(this).attr("setLabel") == '1') {
				label = AJS.$(this).parent().parent().find('.confluence-label span').html();
				AJS.$('#label-delete-form input[name="label"]').val(label);
				AJS.$('#label-delete-form .label-field').html(label);
			} else {
				label = AJS.$('#delete-labels-dialog input[name="label"]').val();
			}
			
			headerText = AJS.I18n.getText("label-management.delete.confirm.message")
				+ " <span class='label-field'></span>"
				+ "<div class='help-link'><a target='_blank' href='"
				+ AJS.I18n.getText("label-management.text.help.link")
				+ "'>" + AJS.I18n.getText("label-management.text.help")
				+ "</a></div>";
			
			AJS.$("#delete-labels-dialog .dialog-title").html(headerText);
			// set label name of header of dialog
			AJS.$('#delete-labels-dialog .dialog-title .label-field').html(label);
			// empty input
			AJS.$('#defaultOnSpace').attr('checked', 'checked');
			// hide error messages
			AJS.$('#label-delete-form .error-row').hide();
			// show dialog
			deleteDialog.show();
		},

		// --------------------Rename Dialog--------------------
		// This is called when ajax completed from rename action
		onRenameLabelByAjaxCompleted = function (data) {
			// if action success then reload page, else show the error message
			if (data.success === true) {

				// build redirect url
				var spaceKey = AJS.$('#label-rename-form input[name="spaceKeyCurrent"]').val(),
					keyParam = '',
					redirectUrl = '';
				if (AJS.$('#rename-bt').length) {
					keyParam = (spaceKey === '') ? '' : spaceKey + "/";
					redirectUrl = Confluence.getContextPath() + "/label/" + keyParam
									+ AJS.$('#label-rename-form input[name="newLabel"]').val();
				} else {
					keyParam = (spaceKey === '') ? '' : '?key=' + spaceKey;
					redirectUrl = Confluence.getContextPath() + "/labels/listlabels-management.action" + keyParam;
				}
				// redirect action
				window.location = redirectUrl;
			} else {
				// show error message
				AJS.$('#label-rename-form #labelOperationErrorMessage').html(data.response);
				AJS.$('#label-rename-form .error-row').show();
			}
		},

		// This function process the submit rename form event 
		onSubmitRenameForm = function () {
			var request = {
				url: Confluence.getContextPath() + "/labels/renamelabel.action",
				data: {},
				dataType: "json",
				type: "GET",
				success: onRenameLabelByAjaxCompleted
			};
			// set request data
			request.data['oldLabel'] = AJS.$('#label-rename-form input[name="oldLabel"]').val();
			request.data['newLabel'] = AJS.$('#label-rename-form input[name="newLabel"]').val();
			request.data['spaceKey'] = AJS.$('#label-rename-form input[name="spaceKey"]:checked').val();
			// call ajax request
			AJS.safe.ajax(request);
		},

		// This function create the rename dialog and bind its events
		initDialogRename = function () {
			renameDialog = AJS.ConfluenceDialog({
				width : 550,
				height : 210,
				id : "rename-labels-dialog",
				closeOnOutsideClick: false
			});
			
			renameDialog.addHeader("");
			
			renameDialog.popup.element.find(".dialog-title").append(Confluence.Templates.Labels.helpLink());
			renameDialog.addPanel("Label Rename", AJS.renderTemplate("labels-dialog-rename"));
			renameDialog.addHelpText(AJS.I18n.getText("label.manager.dialog.rename.tip"));
			renameDialog.addSubmit(AJS.I18n.getText("rename.name"), onSubmitRenameForm);
			renameDialog.addCancel(AJS.I18n.getText("close.name"), function (dialog) {
				AJS.$('.errorMessage').html("");
				dialog.hide();
			});
		},

		// This function show rename dialog
		showRenameDialog = function () {
			// init dialog if necessary
			if (!renameDialog) {
				initDialogRename();
			}
			// set data for the form
			var label,
				headerText = '';
			if (AJS.$(this).attr("setLabel") == 1) {
				label = AJS.$(this).parent().parent().find('.confluence-label span').html();
				AJS.$('#label-rename-form input[name="oldLabel"]').val(label);
				AJS.$('#label-rename-form .label-field').html(label);
			} else {
				label = AJS.$('#rename-labels-dialog input[name="oldLabel"]').val();
			}

			headerText = AJS.I18n.getText("label-management.rename.confirm.message")
				+ " <span class='label-field'></span>"
				+ "<div class='help-link'><a target='_blank' href='"
				+ AJS.I18n.getText("label-management.text.help.link")
				+ "'>" + AJS.I18n.getText("label-management.text.help")
				+ "</a></div>";

			AJS.$("#rename-labels-dialog .dialog-title").html(headerText);
			// set label name of header of dialog
			AJS.$('#rename-labels-dialog .dialog-title .label-field').html(label);
			// empty input
			AJS.$('#label-rename-form input[type="text"]').val('');
			AJS.$('#label-rename-form #defaultOnSpace').attr('checked', 'checked');
			// hide error messages
			AJS.$('#label-rename-form .error-row').hide();
			// show dialog
			renameDialog.show();
		},

		// --------------------Merge Dialog--------------------
		// This is called when ajax completed from merge action
		onMergeLabelByAjaxCompleted = function (data) {
			// if action success then reload page, else show the error message
			if (data.success === true) {
				// build redirect url
				var spaceKey = AJS.$('#label-merge-form input[name="spaceKeyCurrent"]').val(),
					keyParam = '',
					redirectUrl = '';
				if (AJS.$('#merge-bt').length) {
					keyParam = (spaceKey === '') ? '' : spaceKey + "/";
					redirectUrl = Confluence.getContextPath() + "/label/" + keyParam
									+ AJS.$('#label-merge-form input[name="labelsString"]').val();
				} else {
					keyParam = (spaceKey === '') ? '' : '?key=' + spaceKey;
					redirectUrl = Confluence.getContextPath() + "/labels/listlabels-management.action" + keyParam;
				}
				// redirect action
				window.location = redirectUrl;
			} else {
				// show error message
				AJS.$('#label-merge-form #labelOperationErrorMessage').html(data.response);
				AJS.$('#label-merge-form .error-row').show();
			}
		},

		// This function process the submit merge form event 
		onSubmitMergeForm = function () {
			var request = {
				url: Confluence.getContextPath() + "/labels/mergelabel.action",
				data: {},
				dataType: "json",
				type: "GET",
				success: onMergeLabelByAjaxCompleted
			};
			// set request data
			request.data['firstLabel'] = AJS.$('#label-merge-form input[name="firstLabel"]').val();
			request.data['secondLabel'] = AJS.$('#label-merge-form input[name="labelsString"]').val();
			request.data['spaceKey'] = AJS.$('#label-merge-form input[name="spaceKey"]:checked').val();
			// call ajax request
			AJS.safe.ajax(request);
		},

		// This function create the merge dialog and bind its events
		initDialogMerge = function () {
			mergeDialog = AJS.ConfluenceDialog({
				width : 550,
				height : 210,
				id : "merge-labels-dialog",
				closeOnOutsideClick: false
			});
			
			mergeDialog.addHeader("");
			mergeDialog.addPanel("Label Editor", AJS.renderTemplate("labels-dialog-merge"));
			mergeDialog.addHelpText(AJS.I18n.getText("label.manager.dialog.merge.tip"), {shortcut: AJS.$('#label-merge-form input[name="firstLabel"]').val()});	 		
			mergeDialog.addSubmit(AJS.I18n.getText("merge.name"), onSubmitMergeForm);
			mergeDialog.addCancel(AJS.I18n.getText("close.name"), function (dialog) {
				AJS.$('.errorMessage').html("");
				dialog.hide();
			});
			//AJS.$("#merge-labels-dialog").removeClass("aui-popup aui-dialog aui-box-shadow");
			AJS.$("#merge-labels-dialog").addClass("aui-dialog-merge");
			bindAutocomplete();
		},

		// This function show merge dialog
		showMergeDialog = function () {
			// init dialog if necessary
			if (!mergeDialog) {
				initDialogMerge();
			}
			// set data for the form
			var label,
				headerText = '';
			if (AJS.$(this).attr("setLabel") == 1) {
				label = AJS.$(this).parent().parent().find('.confluence-label span').html();
				AJS.$('#label-merge-form input[name="firstLabel"]').val(label);
				AJS.$('#label-merge-form .label-field').html(label);
			} else {
				label = AJS.$('#merge-labels-dialog input[name="firstLabel"]').val();
			}
			
			headerText = AJS.I18n.getText("label-management.merge.confirm.message")
				+ " <span class='label-field'></span>"
				+ "<div class='help-link'><a target='_blank' href='"
				+ AJS.I18n.getText("label-management.text.help.link")
				+ "'>" + AJS.I18n.getText("label-management.text.help")
				+ "</a></div>";
			
			AJS.$("#merge-labels-dialog .dialog-title").html(headerText);
			// set label name of header of dialog
			AJS.$('#merge-labels-dialog .dialog-title .label-field').html(label);
			// empty input
			AJS.$('#label-merge-form input#labelsString').val('');
			AJS.$('#label-merge-form #defaultOnSpace').attr('checked', 'checked');
			// hide error messages
			AJS.$('#label-merge-form .error-row').hide();
			mergeDialog.show();
		},

		// this hacky code was copied from labels.js of Atlassian
		// and just modify the ajax url
		bindAutocomplete = function () {
			var labelInput = $("#labelsString"),
				addLabelOnSelect = labelInput.parents("#label-merge-form").length;

			if (!labelInput.length) {
				return;
			}

			var dropDownPlacement = function (dropDown) {
					$("#labelsAutocompleteList").append(dropDown);
				},

				onselect = function (selection) {
					if (selection.find("a.label-suggestion").length) {

						var span = $("span", selection),
							contentProps = $.data(span[0], "properties"),
							value = labelInput.val(),
							labelArray = [];

						if (addLabelOnSelect) {
							labelArray = value.split(/\s+/);
							labelArray[labelArray.length - 1] = contentProps.name;
							labelInput.val(labelArray.join(' '));
						} else {
							// this hacky code was copied from uberlabels.js
							var tokens = AJS.Labels.queryTokens,
								last_token_pos = -1,
								this_token_pos,
								token = "",
								i = 0,
								ii = 0,
								new_value = '',
								whitespace = '';

							for (i = 0, ii = tokens.length; i < ii; i++) {
								token = tokens[i];
								this_token_pos = value.lastIndexOf(token);

								if (this_token_pos > last_token_pos) {
									last_token_pos = this_token_pos;
								}
							}

							if (last_token_pos != -1) {
								new_value = value.substr(0, last_token_pos);
								whitespace = value.substr(last_token_pos + token.length).match(/^\s+/);
								if (whitespace) {
									new_value += whitespace[0];
								}
								labelInput.val(new_value + contentProps.name);
							} else {
								labelInput.val(contentProps.name);
							}
						}
					}
				},
				onshow = function () {
					if (!$("#labelsAutocompleteList .label-suggestion").length) {
						this.hide();
					} else if (!addLabelOnSelect) {
						// remove hrefs if we're not going to add the label on select
						var labels = $("#labelsAutocompleteList a.label-suggestion"),
							i = 0,
							ii = 0;

						for (i = 0, ii = labels.length; i < ii; i++) {
							labels.get(i).href = "#";
						}
					}
				},
				// url to get auto completed label list with results
				url = "/labels/autocompletelabel.action";

			$(window).bind("quicksearch.ajax-success", function (e, data) {
				if (data.url == url) {
					AJS.Labels.queryTokens = (data.json && data.json.queryTokens) || [];
					return false;
				}
			});
			$(window).bind("quicksearch.ajax-error", function (e, data) {
				if (data.url == url) {
					AJS.Labels.queryTokens = [];
					return false;
				}
			});
			labelInput.quicksearch(url, onshow, {
				makeParams: function (val) {
					return {
						query: val,
						contentId: AJS.params.pageId || ""
					};
				},
				dropdownPlacement : dropDownPlacement,
				ajsDropDownOptions : {
					selectionHandler: function (e, selection) {
						onselect(selection);
						this.hide();
						e.preventDefault();
					}
				}
			});
		};
		// End of the copy from labels.js of Atlassian

	AJS.$('#space-labels-link').attr("href", Confluence.getContextPath() + "/labels/listlabels-management.action?groupRanks=false&key=" + spaceKey);
	AJS.$('#space-labels-link-tab').attr("href", Confluence.getContextPath() + "/labels/listlabels-management.action?groupRanks=false&key=" + spaceKey);

	// prevent submit event of the delete form
	AJS.$("#label-delete-form").submit(function (e) {
		e.preventDefault();
		return false;
	});
	// prevent submit event of the rename form
	AJS.$("#label-rename-form").submit(function (e) {
		e.preventDefault();
		return false;
	});
	// prevent submit event of the merge form
	AJS.$("#label-merge-form").submit(function (e) {
		e.preventDefault();
		return false;
	});

	// bind click event for action links
	AJS.$('.delete-link').click(showDeleteDialog);
	AJS.$('.rename-link').click(showRenameDialog);
	AJS.$('.merge-link').click(showMergeDialog);
});
